package it.uniba.di.mas.jpnde.behaviour;

import it.uniba.di.mas.jpnde.console.IConsoleBackEnd;
import it.uniba.di.mas.jpnde.console.IConsoleUI;
import it.uniba.di.mas.jpnde.core.PN;
import jade.core.behaviours.Behaviour;
import jade.lang.acl.ACLMessage;

public class JPNDEConsoleBehaviour extends Behaviour
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private IConsoleBackEnd consoleBE=null;
	private IConsoleUI console=null;
	
	public JPNDEConsoleBehaviour(IConsoleBackEnd consoleBE,IConsoleUI console){
		this.consoleBE= consoleBE;
		this.console=console;
	}
	
	@Override
	public void action() {
		// TODO Auto-generated method stub
		ACLMessage message=myAgent.receive();
		if (message!=null)
			{
			switch(message.getPerformative())
				{
				case ACLMessage.INFORM:
					for(int i=0;i<consoleBE.getManagedPNs().size();i++){
						PN pn=(PN)consoleBE.getManagedPNs().get(i);
						if (pn.getAgentId().equals(message.getSender().getName()))
							{
							pn.setState(PN.STATE_ENDED);
							console.appendLogMessage("PN<"+pn.getId()+"> ended !");
							console.managedPNsChange();
							break;
							}
					}
					break;
				case ACLMessage.FAILURE:
					for(int i=0;i<consoleBE.getManagedPNs().size();i++){
						PN pn=(PN)consoleBE.getManagedPNs().get(i);
						if (pn.getAgentId().equals(message.getSender().getName()))
							{
							pn.setState(PN.STATE_ERROR);
							console.appendLogMessage("PN<"+pn.getId()+"> error:"+
									message.getContent());
							console.managedPNsChange();
							break;
							}
					}
					break;
				default: 	  
				       System.out.println("JPNDEConsolleBehaviour :"+
					      " performative <"+message.getPerformative()+"> not recognized !");
				}
			}
		else
			block();
	}

	@Override
	public boolean done() {
		// TODO Auto-generated method stub
		boolean ret=true;
		for(int i=0;i<consoleBE.getManagedPNs().size();i++){
			if (((PN)consoleBE.getManagedPNs().get(i)).getState().equals(PN.STATE_STARTING))
				return true;
			if (((PN)consoleBE.getManagedPNs().get(i)).getState().equals(PN.STATE_RUNNING))
				ret=false;
		}
		return ret;
	}
	
	public int onEnd() {
		int ret=super.onEnd();
		System.out.println("JPNDEConsolleBehaviour.onEnd :"+myAgent.getAID().getName());
		return ret;
	}
}

